package com.zlsy.learning.leetcode.linkedlist.l19;

import com.zlsy.learning.leetcode.linkedlist.l234.ListNode;

/**
 * @author zhouliang
 * @date 2020/8/6 20:56
 */
public class RemoveNthFromEnd {

  private static ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    int length = 0;
    ListNode first = head;
    while (first != null) {
      length++;
      first = first.next;
    }
    length -= n;
    first = dummy;
    while (length > 0) {
      length--;
      first = first.next;
    }
    //摘除要删除的节点
    first.next = first.next.next;
    return dummy.next;
  }

  public static void main(String[] args) {
      ListNode listNode =new ListNode(1);
      listNode.add(2);
      listNode.add(3);
      listNode.add(4);
      listNode.add(5);

      ListNode listNode1 = removeNthFromEnd(listNode, 2);
      listNode1.print();
  }
}
